<template>
  <div class="WeChat">
    <el-container class="main-container">
      <Toolbar
        :select="select"
        :is-online="isOnline"
        :avatar="$store.getters?.userLogin?.avatar || require('@/assets/icon/default-avatar.svg').default"
        @switch-tool="switchTool"
        @open-dynamic="dynamic"
        @open-settings="openSettings"
        @logout="logout"
      ></Toolbar>
      <el-aside class="sidebar sidebar-styles">
        <el-header height="60px" class="header-styles">
          <SearchModule
            :disabled="select === 2"
            :show-switching="showSwitching"
            @search="handleSearch"
            @focus="handleSearchFocus"
            @blur="handleSearchBlur"
            @clear="completeSearch"
            @command="handleCommand"
            @switch-show="switchShow"
            ref="searchModule"
          />
        </el-header>
        <!--好友消息-->
        <MaskIMChatList
          v-show="select === 1"
          v-if="chatFlag"
          @currentFriend="currentFriend"
          @groupDetail="groupDetail"
          @completeSearch="completeSearch"
          ref="asideFriend"
        />

        <!--好友详情-->
        <MaskIMContactList
          ref="asideFriendDetail"
          v-show="select === 2 || select === 4 || select === 5"
          v-if="friendFlag"
          @friendMessage="friendMessage"
          @show-friend-verification="showFriendVerification"
        />

        <!-- <MaskIMGroupList
          ref="groupList"
          v-show="select === 3 || select === 4"
          v-if="friendFlag"
          @friendMessage="friendMessage"
        /> -->
      </el-aside>

      <el-container
        v-show="
          (this.item.friendshipId && this.select === 1) ||
          (this.friendDetailId !== null && this.select === 2) ||
          (this.groupDetailId !== null && this.select === 4) ||
          (this.select === 5)
        "
      >
        <el-header
          class="my-header chat-header-styles"
          v-show="this.select === 1"
        >
          <div class="header-content-layout">
            <div>
              <span>{{ item.remark }}</span
              >&nbsp;
              <span v-if="this.item.type === 0"
                >({{ this.item.groupChatCount }})</span
              >
            </div>
            <div class="callFriend">
              <div
                v-if="item.type === 1 && animation"
                class="transition-box call-buttons-layout"
              >
                <div
                  class="voice function"
                  @click="operationCommand('voiceCalls')"
                >
                  <el-tooltip
                    class="item"
                    :open-delay="400"
                    effect="light"
                    content="语音通话"
                    placement="bottom"
                  >
                    <span class="el-icon-phone-outline"></span>
                  </el-tooltip>
                </div>
                <el-divider direction="vertical"></el-divider>
                <div
                  class="video function"
                  @click="operationCommand('videoCalls')"
                >
                  <el-tooltip
                    class="item"
                    :open-delay="400"
                    effect="light"
                    content="视频通话"
                    placement="bottom"
                  >
                    <span class="el-icon-video-camera"></span>
                  </el-tooltip>
                </div>
              </div>
              <el-tooltip
                :disabled="true"
                placement="left"
                effect="light"
                v-show="item.type === 0"
              >
                <el-popover placement="bottom" width="300" trigger="click">
                  <span
                    class="bell"
                    slot="reference"
                    @click.prevent="getGroupMembers(item.friendshipId)"
                  >
                    <i class="el-icon-more"></i>
                  </span>
                  <el-scrollbar>
                    <ChatGroupMember
                      :total="this.total"
                      ref="chatGroupMember"
                      :loadingMore="this.loadingMore"
                      :loadFlag="this.loadFlag"
                      :item="this.item"
                    />
                  </el-scrollbar>
                </el-popover>
              </el-tooltip>
            </div>
          </div>
        </el-header>
        <el-main class="main-content-padding">
          <ChatBox ref="chatBox" v-show="this.select === 1" />
          <FriendDetail
            ref="friendDetail"
            @initFriendDetailId="initFriendDetailId"
            @chatView="chatView"
            :select="select"
            v-show="this.select === 2 && this.friendDetailId !== null"
          />
          <GroupDetail
            ref="groupDetail"
            @initGroupDetailId="initGroupDetailId"
            @groupChat="groupChat"
            :select="select"
            v-show="this.select === 4 && this.groupDetailId !== null"
          />
          <FriendVerification
            ref="friendVerification"
            v-show="this.select === 5"
            @friend-accepted="handleFriendAccepted"
          />
        </el-main>
      </el-container>
      <!-- 初始LOGO-->
      <el-container
       v-if="this.select == null"
        class="logo-container-layout"
      >
        <div class="logo-content-layout">
          <!-- logo图标 -->
          <!-- <WechatFriend/> -->
          <div class="WeChatLOGO"></div>
        </div>
      </el-container>
    </el-container>

    <!-- 弹窗管理器 -->
    <DialogManager
      :precision-search-view.sync="precisionSearchView"
      :build-group-chat.sync="buildGroupChat"
      :dialog-visible-video.sync="dialogVisibleVideo"
      :dialog-visible-voice.sync="dialogVisibleVoice"
      :dialog-visible-dynamic.sync="dialogVisibleDynamic"
      :dialog-visible-own-dynamics.sync="dialogVisibleownDynamics"
      :post-news-show.sync="postNewsShow"
      :dynamic-view-show.sync="dynamicViewShow"
      :show-settings-dialog.sync="showSettingsDialog"
      :current-item="item"
      @complete-search="completeSearch"
      @precision-search="precisionSearch"
      @clear-video-timer="clearVideoTimer"
      @clear-voice-timer="clearVoiceTimer"
      ref="dialogManager"
    />
  </div>
</template>

<script>
import MaskIMChatList from "../../components/Wechat/ChatList.vue";
import MaskIMContactList from "../../components/Wechat/ContactList";
import FriendVerification from "../../components/Wechat/FriendVerification";
import FriendDetail from "../../components/Wechat/FriendDetail";
import GroupDetail from "../../components/Wechat/GroupDetail";
import ChatBox from "../../components/ChatBox";
import service from "../../utils/request";
import ChatGroupMember from "../../components/Wechat/ChatGroupMember";
import Toolbar from "../../components/Common/Toolbar";

// 拆分后的组件
import SearchModule from "../../components/Wechat/SearchModule.vue";
import DialogManager from "../../components/Wechat/DialogManager.vue";

// 混入和服务
import StateManager from "../../mixins/StateManager";
import { WebSocketManager } from "../../services/WebSocketManager";

export default {
  name: 'WeChat',
  mixins: [StateManager],
  components: {
    ChatBox,
    MaskIMChatList,
    ChatGroupMember,
    MaskIMContactList,
    FriendDetail,
    GroupDetail,
    FriendVerification,
    Toolbar,
    SearchModule,
    DialogManager,
  },
  data() {
    return {
      // WebSocket管理器实例
      webSocketManager: null,
    };
  },
  
  methods: {
    // 搜索相关方法
    handleSearch(keyword) {
      // 搜索逻辑已在SearchModule中处理
    },
    
    handleSearchFocus() {
      // 聚焦逻辑已在SearchModule中处理
    },
    
    handleSearchBlur() {
      // 失焦逻辑已在SearchModule中处理
    },
    
    // 转账相关方法
    changeTransferModel() {
      this.showTransferDialog = false;
    },
    
    confirmTransferModel(transferMoney) {
      this.confirmTransferBtnLoading = true;
      service({
        method: "post",
        url: "/friend_chat/transfer",
        data: transferMoney,
      })
        .then((res) => {
          if (res.flag) {
            this.$notify({
              title: "转账",
              type: "success",
              message: "转账成功",
            });
            this.showTransferDialog = false;
          } else {
            this.$notify({
              title: "转账",
              type: "error",
              message: res.message || "转账失败",
            });
          }
        })
        .catch((error) => {
          console.error('转账失败:', error);
          this.$notify({
            title: "转账",
            type: "error",
            message: "网络错误，请稍后重试",
          });
        })
        .finally(() => {
          this.confirmTransferBtnLoading = false;
        });
    },
    // 群组成员管理
    getGroupMembers(groupId) {
      this.safeRefCall('chatGroupMember', 'getGroupMembers', groupId);
    },
    currentFriend(event) {
      try {
        this.item = event;
        // 使用新的状态管理设置当前聊天
        this.$store.dispatch("chat/setCurrentChat", this.item);
        if (this.item.type === 0) {
          this.safeRefCall('chatGroupMember', 'getIsGroupLeader', this.item.friendshipId);
          this.safeRefCall('chatGroupMember', 'groupChatMessageList', this.item.friendshipId);
        }
        this.safeRefCall('chatBox', 'chatBox', this.item);
      } catch (error) {
        console.error('设置当前聊天失败:', error);
        this.$errorHandler?.handleError(error, {
          component: 'WeChat',
          method: 'currentFriend',
          data: { event, item: this.item }
        });
        this.$notify({
          title: '操作失败',
          message: '无法切换到该聊天',
          type: 'error'
        });
      }
    },
    friendMessage(event) {
      if (event.type === 1) {
        // 检查是否是群聊
        if (event.chatType === 2 || event.groupChatCount > 0) {
          // 这是群聊，显示群聊详情
          this.groupDetailId = event.groupId || event.friendId;
          this.select = 4;
          this.$store.commit("updateToolbarSelectState", this.select);
          this.safeRefCall('groupDetail', 'initGroupMessage', event);
        } else {
          // 这是好友，显示好友详情
          this.friendDetailId = event.id;
          this.select = 2;
          this.$store.commit("updateToolbarSelectState", this.select);
          this.safeRefCall('friendDetail', 'friendMessageItem', this.friendDetailId);
        }
      } else if (event.type === 0) {
        this.select = 1;
        this.friendDetailId = null;
        this.groupDetailId = null;
        // this.chatFlag = false;
        this.$store.commit("updateToolbarSelectState", this.select);
        // this.$nextTick(()=>{
        //     this.chatFlag = true
        // });
        this.safeRefCall('asideFriend', 'getChat', event);
      }
    },
    // 搜索完成
    completeSearch() {
      try {
        // 防止递归调用
        if (this._completingSearch) {
          return;
        }
        this._completingSearch = true;
        
        if (this.$refs.searchModule) {
          this.$refs.searchModule.completeSearch();
        }
        
        // 重置标志
        this.$nextTick(() => {
          this._completingSearch = false;
        });
      } catch (error) {
        console.error('搜索完成失败:', error);
        this.$errorHandler?.handleError(error, {
          component: 'WeChat',
          method: 'completeSearch',
          data: this.$data
        });
        this._completingSearch = false;
      }
    },
    handleCommand(command) {
      switch (command) {
        case "addFriend":
          this.precisionSearchView = true;
          break;
        case "addGroup":
          this.$router.replace({
            path: "/informationall",
            query: {
              activeName: "group",
            },
          });
          break;
        case "buildGroupChat":
          this.buildGroupChat = true;
          break;
      }
    },
    // 操作命令处理
    operationCommand(command) {
      switch (command) {
        case "transferMoney":
          this.showTransferDialog = true;
          break;
        case "notifyOnline":
          this.webSocketManager.notifyFriendOnline(this.item.friendshipId);
          break;
        case "videoCalls":
          this.webSocketManager.initiateVideoCall(this.item.friendshipId);
          break;
        case "voiceCalls":
          this.webSocketManager.initiateVoiceCall(this.item.friendshipId);
          break;
      }
    },
    // 显示切换
    switchShow(showSwitching) {
      this.select = 1;
      this.showSwitching = showSwitching;
      localStorage.setItem("showSwitching", showSwitching);
      this.$store.dispatch('chatList/fetchChatList');
    },
    
    // 精确搜索
    precisionSearch(searchResult) {
      this.safeRefCall('asideFriend', 'clickAddSession', searchResult);
    },
    chatView(friendItem) {
      this.select = 1;
      this.safeRefCall('asideFriend', 'getChat', friendItem);
    },
    // 群聊详情页面
    groupDetail(groupData) {
      this.groupDetailId = groupData.groupId || groupData.targetId;
      this.select = 4;
      this.$store.commit("updateToolbarSelectState", this.select);
      this.safeRefCall('groupDetail', 'initGroupMessage', groupData);
    },
    // 群聊聊天页面
    groupChat(groupData) {

      this.select = 1;
      this.groupDetailId = null;
      this.$store.commit("updateToolbarSelectState", this.select);
      this.safeRefCall('asideFriend', 'getChat', groupData);
    },
    switchTool(type) {
      this.select = type;
      this.$store.commit("updateToolbarSelectState", this.select);
      // 通过SearchModule组件取消焦点
      if (this.$refs.searchModule && this.$refs.searchModule.handleClear) {
        this.$refs.searchModule.handleClear();
      }
    },
    // 动态相关
    dynamic() {
      this.dialogVisibleDynamic = true;
    },
    
    // 设置
    openSettings() {
      this.showSettingsDialog = true;
    },
    logout() {
      this.$confirm("是否退出当前登录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          service.post("/userAuth/logout").then((res) => {
            if (res.code === 200) {
              this.$store.dispatch("user/resetToken");
              this.$router.replace("/login");
            } else {
              this.$notify({
                title: "退出登入",
                type: "warning",
                message: "退出失败",
              });
            }
          });
        })
        .catch(() => {});
    },
    // Socket命令处理
    handle(command) {
      this.webSocketManager.handleSocketCommand(command);
    },
    
    // 好友验证相关方法
    showFriendVerification() {
      this.updateToolbarSelect(5);
    },
    
    handleFriendAccepted(friendData) {
      this.$message.success("已同意好友申请");
      this.$store.dispatch('contactList/loadAllContacts');
      
      if (friendData.friendId) {
        this.updateToolbarSelect(1);
      }
    },
    
  },
  
  mounted() {
    try {
      // 初始化WebSocket管理器
      this.webSocketManager = new WebSocketManager(this);
      this.webSocketManager.init();
      
      // 处理路由参数
      if (this.$route.query.friendId && this.$route.query.remark) {
        const params = {
          friendId: this.$route.query.friendId,
          remark: this.$route.query.remark,
          userInfoId: this.$route.query.userInfoId,
      };
      this.updateToolbarSelect(1);
      this.safeRefCall('asideFriend', 'clickAddSession', params);
    }
    } catch (error) {
      console.error('WeChat mounted error:', error);
      this.$errorHandler?.handleError(error, {
        component: 'WeChat',
        method: 'mounted',
        data: this.$data
      });
      
      // 显示用户友好的错误信息
      this.$notify({
        title: '初始化失败',
        message: '应用初始化时出现错误，请刷新页面重试',
        type: 'error',
        duration: 5000
      });
    }
  },
  
  beforeDestroy() {
    // 销毁WebSocket管理器
    if (this.webSocketManager) {
      this.webSocketManager.destroy();
      this.webSocketManager = null;
    }
    
    // 清理数据引用，防止内存泄漏
    this.item = {};
    this.friendDetailId = null;
    this.groupDetailId = null;
    
    // 不要手动置空 $store（Vue 注入对象），避免潜在异常
  },
};
</script>

<style scoped>
.WeChat {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  /* padding: 5px; */
}

.WeChat-left {
  width: 240px;
  height: 100%;
  background-image: linear-gradient(#3dbcfd, #97dbfe, #30d791);
}

.my-header {
  box-shadow: 0 4px 4px rgba(0, 0, 0, 0.1);
}

::v-deep .el-card__body,
.el-main {
  padding-top: 5px !important;
}

.el-header {
  background-color: #f5f5f5;
  color: #333;
  height: 50px !important;
  line-height: 50px;
}

.sidebar {
  overflow: hidden; /* 隐藏滚动条 */
}

::v-deep .el-aside {
  color: #e4e4e4;
}

::v-deep .el-card__body {
  padding: 0 !important;
}

.header-R {
  line-height: 50px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

::v-deep .header-R .el-button {
  margin-left: 10px;
  padding: 5px 5px;
  background-color: #f3f3f3;
}

::v-deep .header-R .el-input__inner {
  background-color: #f3f3f3;
}

::v-deep .header-R .el-input__inner:focus {
  border-color: #f3f3f3;
}

::v-deep .custom-badge-online .el-badge__content.is-fixed.is-dot {
  right: 5px;
  top: 38px;
  background-color: #3bb54a;
  height: 10px;
  width: 10px;
  cursor: pointer;
}

::v-deep .custom-badge-off .el-badge__content.is-fixed.is-dot {
  right: 5px;
  top: 38px;
  background-color: #999999;
  height: 10px;
  width: 10px;
  cursor: pointer;
}

.clear {
  background-color: #d1d1d1;
  cursor: pointer;
  color: #999999;
  font-weight: bold;
  border-radius: 50%;
  padding: 1px;
}

.clear :hover {
  color: #7e7e7e;
}

.function-content {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.function-icon {
  cursor: pointer;
  width: 40px;
  height: 40px;
}

.function-icon:hover {
  transition: 0.5s;
  transform: scale(1.1);
}

.operation {
  margin-left: auto;
  font-size: 22px;
}

.operation:hover {
  cursor: pointer;
  color: #999999;
}

.callFriend {
  display: flex;
  margin-left: auto;
}

.callFriend .bell {
  font-size: 18px;
  cursor: pointer;
}

.callFriend .bell:hover {
  color: #1ab8b8;
}

::v-deep .el-popover {
  padding: 0 !important;
}

.WeChatLOGO {
  background-image: -webkit-linear-gradient(top, #bc8550, #d77f34, #de6912);
  background-image: linear-gradient(to bottom, #bc8550, #d77f34, #de6912);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 6em;
  font-weight: bold;
  height: 100%;
  color: #dadada;
  font-family: "PingFang SC", serif;
}

.transition-box {
  margin-bottom: 10px;
  /* width: 260px; */
  height: 100px;
  border-radius: 4px;
  background-color: white;
  text-align: center;
  z-index: 0 !important;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}

.toolbar {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 25px;
  min-width: 50px;
  background-color: #252525;

  /* background-color: #525252; */
}

.toolbar-spacer {
  flex-grow: 1; /* 这会让占位元素占据所有可用空间，将下面的工具推到底部 */
}

.toolbar .tool,
.toolFocus {
  font-size: 25px;
  cursor: pointer;
}

.toolbar .tool {
  color: #bfbfbf;
  margin-top: 70px;
}

.toolbar .toolFocus {
  color: #0badf9;
}

.toolbar .tool:hover {
  color: #d8d8d8;
}

.toolbar .toolFocus:hover {
  color: #15c2ff;
}

.tool-operation {
  margin-top: 420px;
  cursor: pointer;
  color: #d8d8d8;
}

.tool-operation:hover {
  color: #fff;
}

.voice {
  cursor: pointer;
  font-size: 23px;
  margin: 0 15px 0 15px;
}

.voice:hover {
  transition: 0.4s;
  transform: scale(1.2);
  color: #000000;
}

.video {
  cursor: pointer;
  font-size: 23px;
  margin: 0 15px 0 15px;
}

.video:hover {
  transition: 0.4s;
  transform: scale(1.2);
  color: #000000;
}

.prompt {
  cursor: pointer;
  font-size: 23px;
  margin: 0 15px 0 15px;
}

.prompt:hover {
  transition: 0.4s;
  transform: scale(1.2);
  color: #000000;
}

.red-envelope {
  margin: 0 15px 0 15px;
  cursor: pointer;
}

.red-envelope:hover {
  cursor: pointer;
  transition: 0.4s;
  transform: scale(1.2);
  color: #000000;
}

.flexible {
  cursor: pointer;
  font-size: 23px;
  margin: 0 0 0 15px;
}

.transition-box {
  margin-bottom: 0;
  height: 50px;
  border-radius: 0;
  background-color: revert;
  color: #494949;
  padding: 0;
  margin-right: 0;
}

/* 提取的内联样式 */
.main-container {
  height: 100%;
  border: 1px solid #eee;
}

.sidebar-styles {
  background-color: #f5f7fa;
  border-right: 1px solid #e7e7e7;
}

.header-styles {
  background-color: #ffffff;
  border-bottom: 1px solid #e2e2e2;
  position: relative;
}

.search-input-width {
  width: 85%;
}

.setting-icon-bold {
  font-weight: bold;
}

.chat-header-styles {
  background-color: #ffffff;
  border-bottom: 1px solid #e1e1e1;
}

.header-content-layout {
  display: flex;
  flex-direction: row;
  align-items: center;
  position: relative;
}

.call-buttons-layout {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.main-content-padding {
  padding: 0;
  height: calc(100vh - 60px); /* 减去header高度 */
  overflow: hidden; /* 防止整个页面滚动 */
}

.logo-container-layout {
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-content-layout {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.dialog-content-layout {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.dialog-input-width {
  width: 300px;
}
</style>
